<?php
namespace app\admin\controller;
class Staff extends Common
{
    public function lst(){
        $groupId=input()['group_id'];
        $status = isset(input()['status'])?input()['status']:1;
        $adminRes=db('admin')->alias('a')->field('a.*,b.title')->join('auth_group b','a.group_id=b.id')->where('group_id','<>','1');
        $count=db('admin')->where('group_id','<>','1');
        $keywords = input()['keywords'];
        if($groupId != 1 && $groupId)
        {
            $adminRes = $adminRes->where('group_id',$groupId);
            $count = $count->where('group_id',$groupId);
        }
        if($keywords)
        {
			$adminRes = $adminRes->where('a.name|a.username','LIKE',"%{$keywords}%");
			$count = $count->where('name|username','LIKE',"%{$keywords}%");
        }
        if(isset($status))
        {
            $adminRes = $adminRes->where('a.status',$status);
            $count = $count->where('status',$status);
        }
        //主管
        if(session('group_id','','admin')==5)
        {
            $groupMembers = db('admin')->where('id',session('uid','','admin'))->value('group_members');
            if($groupMembers)
            {
                $adminRes = $adminRes->where('a.id','IN',$groupMembers.','.session('uid','','admin') );
            }
            else
            {
                $adminRes = $adminRes->where('a.id','IN',session('uid','','admin') );
            }
        }
        $adminRes = $adminRes->order('id DESC')->paginate(10,false,['query'=>$this->request->param()]) 
                    ->each(function($item, $key){
                        $item['today_count'] = db('client')->where('aid',$item['id'])->whereTime('add_time','today')->count();
                        return $item;
                    });
        $count = $count->count();
        $this->assign([
            'adminRes'=>$adminRes,
            'count'=>$count,
            'groupId'=>$groupId
        ]);
        return view();
    }
    
    public function add()
    {
    	if(request()->isAjax()){
    		$data=input('post.')['data'];
    		$data['salt']=mt_rand(1000,9999);
            $data['password']=md5(md5($data['password']).$data['salt']);
            $data['create_time']=time();
            $data['join_time'] = strtotime($data['join_time']);
            //添加数据到admin表，并返回id
            $add=db('admin')->insertGetId($data);
            //对应员工和用户组id
            $_data=array();
            $_data['uid']=$add;
            $_data['group_id']=$data['group_id'];
            //添加用户组明细表信息
            $addGroupAccess=db('authGroupAccess')->insert($_data);
            if($add && $addGroupAccess)
            {
                if(session('group_id','','admin')==5)
                {
                    $groupMembers = db('admin')->where('id',session('uid','','admin'))->value('group_members');
                    $groupMembers = $groupMembers?$groupMembers.','.session('uid','','admin'):session('uid','','admin');
                    db('admin')->where('id',session('uid','','admin'))->update(['group_members'=>$groupMembers ] );
                }

                return ['msg'=>'新增员工成功','icon'=>1];
            }else{
                return ['msg'=>'新增员工失败','icon'=>2];
            }
            return;
    	}
        $groupRes=db('authGroup')->where('id','<>','1')->field('id,title,status')->select();
        $staffList = $this->getStaffTransferData();
        $this->assign([
            'groupRes'=>$groupRes,
            'staffList'=>$staffList,
        ]);
        return view();
    }


    public function edit()
    {
        if(request()->isAjax()){
            $data=input('post.')['data'];
            if($data['password'] !== '' || $data['repass'] !== ''){
                if($data['password'] !== $data['repass']){
                    return ['msg'=>'两次密码输入不一致','icon'=>5];
                }
            }
            $data['join_time'] = strtotime($data['join_time']);
            unset($data['repass']);
            //查询密钥
            $userInfo=db('admin')->where('id',$data['id'])->find();
            $salt=$userInfo['salt'];
            if($data['password']){
                $data['password']=md5(md5($data['password']).$salt);
            }else{
                unset($data['password']);
            }
            $save=db('admin')->update($data);
            //添加auth权限 用户组明细表内容
            db('authGroupAccess')->where(array('uid'=>$data['id']))->update(['group_id'=>$data['group_id']]);
            if($save !== false){
                return ['msg'=>'编辑员工成功','icon'=>1];
            }else{
                return ['msg'=>'编辑员工失败','icon'=>2];
            }
            return;
        }
        $groupRes=db('authGroup')->select();
    	$admins=db('admin')->find(input('id'));
        $staffList = $this->getStaffTransferData($admins['group_members']);
    	$this->assign([
    		'admins'=>$admins,
            'groupRes'=>$groupRes,
            'staffList'=>$staffList
    	]);
        return view();
    }

    public function del()
    {
        if(request()->isAjax()){
            $id=input('id');
        	if($id == 1){
        		return json(['msg'=>'超级员工不允许删除','icon'=>2]);
        	}else{
                //删除auth权限用户组明细表内容
                db('authGroupAccess')->where(array('uid'=>$id))->delete();
        		$del=db('admin')->delete($id);
        		if($del){
                    return ['msg'=>'删除员工成功','icon'=>1];
        		}else{
        			return ['msg'=>'删除员工失败','icon'=>2];
        		}
        	}
        }
    }
    //批量删除
    // public function delAll()
    // {
    //     if(request()->isAjax()){
    //         $data=input('post.')['data'];
    //         $data= array_filter($data);
    //         foreach ($data as $k => $v){
    //             //删除auth权限用户组明细表内容
    //             db('authGroupAccess')->where(array('uid'=>$v))->delete();
    //             $del=db('admin')->delete($v);
    //         }
    //         return ['msg'=>'批量删除员工成功','icon'=>1];
    //     } 
    // }
    
    //ajax更新开启状态
    public function changeStatus()
    {
        if(request()->isAjax()){
            $id=input('id');
            $status=input('status');
            if($status == 1){
                db('admin')->where(['id'=>$id])->update(['status'=>0]);
                return ['msg'=>'已禁用','icon'=>2];
            }else{
                db('admin')->where(['id'=>$id])->update(['status'=>1]);
                return ['msg'=>'已启用','icon'=>1];
            }
        }else{
            $this->error("非法操作！");
        }
    }
    
    public function yeji()
    {
        $aid = input('aid')?input('aid'):session('uid','','admin');
        $startDate = input('startDate')?strtotime(input('startDate')):'';
        $endDate = input('endDate')?strtotime(input('endDate'))+86399:'';
        $status = input('status');
        $config['query'] = ['aid'=>$aid,'startDate'=>$startDate,'endDate'=>$endDate,'status'=>$status];
        $clientRes=db('client')->alias('c')->field('c.*,a.name as aname')->join('admin a','a.id=c.xaid')->where('c.status','<>','0')->where('c.xaid',$aid)->order('c.id desc');

        if($startDate || $endDate)
        {
            $dateRange = [$startDate?$startDate:0,$endDate?$endDate:time()];

            $count=db('client')->where('status','<>','0')->where('xaid',$aid)->where('add_time','between',$dateRange)->count();
            $qiandan=db('client')->where('status','4')->where('xaid',$aid)->where('add_time','between',$dateRange)->count();
            $luru=db('client')->where('aid',$aid)->where('add_time','between',$dateRange)->count();
            $clientRes = $clientRes->where('c.add_time','between',$dateRange);
            if($startDate)
            $this->assign(['startDate' => date('Y-m-d',$startDate)]);
            if($endDate)
            $this->assign(['endDate' => date('Y-m-d',$endDate)]);  
        }
        else
        {
            $count=db('client')->where('status','<>','0')->where('xaid',$aid)->count();
            $qiandan=db('client')->where('status','4')->where('xaid',$aid)->count();
            $luru=db('client')->where('aid',$aid)->count();
            
            /*本周*/
            $z_count=db('client')->where('status','<>','0')->where('xaid',$aid)->whereTime('add_time','week')->count();
            $z_qiandan=db('client')->where('status','4')->where('xaid',$aid)->whereTime('add_time','week')->count();
            $z_luru=db('client')->where('aid',$aid)->whereTime('add_time','week')->count();
            
            /*本月*/
            /*周*/
            $y_count=db('client')->where('status','<>','0')->where('xaid',$aid)->whereTime('add_time','month')->count();
            $y_qiandan=db('client')->where('status','4')->where('xaid',$aid)->whereTime('add_time','month')->count();
            $y_luru=db('client')->where('aid',$aid)->whereTime('add_time','month')->count();
        }
        if($status)
        {
            $clientRes = $clientRes->where('c.status',$status);
        }
        $clientRes = $clientRes->paginate(10,false,$config);

        $this->assign([
            'aid' => $aid,
            'status' => $status,
            'clientRes'=>$clientRes,
            'count'=>$count,
            'qiandan'=>$qiandan,
            'luru'=>$luru,
            'z_count'=>$z_count,
            'z_qiandan'=>$z_qiandan,
            'z_luru'=>$z_luru,
            'y_count'=>$y_count,
            'y_qiandan'=>$y_qiandan,
            'y_luru'=>$y_luru,
        ]);
        return view();
    }
    
    public function ip_log()
    {
        $ipText = get_client_ip();
        $list = db('ip_log')->where('status','<',1)->group('admin_id')->select();
        $this->assign(['ip_text'=>$ipText,'list'=>$list]);
        return view();
    }
    
    public function ip_log_status()
    {
        $status = input()['status'];
        $ip = input()['ip'];
        $check = db('ip_log')->where('ip',$ip)->update(['status'=>1]);
        if($check)
            $this->success("操作成功！");
        else
            $this->error("非法操作！");
        
    }


    public function job_list()
    {
        if(input('page'))
        {
            $list = db('staff_job')->where('status','<>','-1')->order('sort ASC,id DESC')->page(input('page'),input('limit'))->select();
            $count = db('staff_job')->where('status','<>','-1')->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
        {
            return view();
        }
    }
    

    public function job_edit()
    {
        if(input('post.'))
        {
            $data = input('post.');
            if(input('id'))
            {
                $sqlStatus = db('staff_job')->where('id',input('id'))->update($data);
            }
            else
            {
                $sqlStatus = db('staff_job')->insert($data);
            }
            return $sqlStatus?['msg'=>'操作成功','icon'=>1,'code'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else 
        {
            if(input('id'))
            {
                $data = db('staff_job')->where('id',input('id'))->find();
            }
            
            $this->assign([
                'data'=>$data,
            ]);
            return view();
        }
        
    }
    
    public function job_setField()
    {
        if(input('field') && input('id') )
        {
            $id = input()['id'];
            if(input('field'))
            {
                $field = input()['field'];
                $value = input()['value'];
                $sqlStatus = db('staff_job')->where('id',$id)->update([ $field=>$value ]);
            }
            else if(input('post.'))
            {
                $data = input('post.');
                $sqlStatus = db('staff_job')->where('id',$id)->update($data);
            }
            return ['msg'=>'操作成功','icon'=>1,'code'=>1];
            
        }
    }


    
    
    
}